<?php

namespace apiend\modules\shop\models;

use Yii;
use yii\db\Exception;
use common\models\shop\ShopCart;
use common\models\shop\ShopFavorite;

/**
 * 购物车内容删除
 * 
 * @author emhome<emhome@163.com>
 * @since 2.0
 */
class CartCollectForm extends \common\base\Model {

    /**
     * @var integer 下单用户ID
     */
    public $user_id;

    /**
     * @var array 结算内容单元
     */
    public $ids;

    /**
     * @var array 待结算SKU
     */
    private $_carts = [];

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['ids'], 'required'],
            [['ids'], 'string'],
            [['user_id'], 'integer'],
            [['ids'], 'validateItems'],
        ];
    }

    /**
     * 校验提交商品的信息
     * @param string $attribute the attribute currently being validated
     */
    public function validateItems($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $items = array_unique(explode(',', $this->$attribute));
        if (empty($items)) {
            return $this->addError($attribute, '请选择要收藏的购物车商品');
        }
        $carts = $this->loadCartItems($items);
        if (empty($carts)) {
            return $this->addError($attribute, '不存在操作的内容');
        }
        $this->_carts = $carts;
    }

    /**
     * 获取待结算内容
     * @return boolean
     */
    public function loadCartItems($ids) {
        $query = ShopCart::findActive('t')->andWhere([
            't.user_id' => $this->user_id,
            't.id' => $ids,
        ]);
        return $query->all();
    }

    /**
     * 删除保存
     * @return array
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError('购物车商品加入收藏时失败');
        }
        $carts = $this->_carts;
        $transaction = Yii::$app->db->beginTransaction();
        try {
            foreach ($carts as $cart) {
                $model = ShopFavorite::findOrNew([
                    'user_id' => $cart->user_id,
                    'product_id' => $cart->product_id,
                ]);
                $model->goods_id = $cart->goods_id;
                if (!$model->save()) {
                    throw new Exception('商品收藏失败');
                }
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            return $this->dumpError($e->getMessage(), false);
        }
        return true;
    }

}
